import { ref } from "vue";

export interface PickingGroup {
  address: {
    receiverName: string;
    receiverPhone: string;
    receiverProvince: string;
    receiverCity: string;
    receiverDistrict: string;
    receiverAddress: string;
    postcode?: string;
  };
  orders: Array<{
    orderInfo: {
      orderNo: string;
      remark?: string;
    };
    items: Array<{
      spuName: string;
      skuSpecs: string;
      skuNumber: number;
      unitPrice: number;
      totalPrice: number;
    }>;
  }>;
  orderNos: string[];
  totalQuantity: number;
  totalAmount: number;
}

export function useCsvExport() {
  const isExporting = ref(false);

  // CSV字段转义处理
  const escapeCsvField = (field: any): string => {
    if (field === null || field === undefined) {
      return "";
    }

    const stringField = String(field);
    // 如果包含逗号、换行符或引号，需要用引号括起来
    if (
      stringField.includes(",") ||
      stringField.includes("\n") ||
      stringField.includes('"')
    ) {
      return `"${stringField.replace(/"/g, '""')}"`;
    }

    return stringField;
  };

  // 格式化规格信息
  const formatSpecs = (skuSpecs: string): string => {
    try {
      const specs = JSON.parse(skuSpecs);
      return Object.entries(specs)
        .map(([key, value]) => `${key}:${value}`)
        .join("; ");
    } catch (e) {
      return skuSpecs;
    }
  };

  // 构建配货单CSV内容
  const buildPickingCsvContent = (pickingGroups: PickingGroup[]): string => {
    const csvLines: string[] = [];

    // 添加CSV头部（BOM头解决中文乱码）
    csvLines.push("\uFEFF");
    csvLines.push(
      "收货人,电话,省份,城市,区县,详细地址,邮编,订单号,商品名称,规格,数量,单价,金额,备注"
    );

    // 处理每个配货组
    pickingGroups.forEach((group) => {
      const address = group.address;

      // 处理组内的每个订单
      group.orders.forEach((order) => {
        // 处理订单中的每个商品
        order.items.forEach((item) => {
          const csvLine = [
            escapeCsvField(address.receiverName),
            escapeCsvField(address.receiverPhone),
            escapeCsvField(address.receiverProvince),
            escapeCsvField(address.receiverCity),
            escapeCsvField(address.receiverDistrict),
            escapeCsvField(address.receiverAddress),
            escapeCsvField(address.postcode || ""),
            escapeCsvField(order.orderInfo.orderNo),
            escapeCsvField(item.spuName),
            escapeCsvField(formatSpecs(item.skuSpecs)),
            item.skuNumber,
            item.unitPrice,
            item.totalPrice,
            escapeCsvField(order.orderInfo.remark || ""),
          ];

          csvLines.push(csvLine.join(","));
        });
      });

      // 添加分组汇总行
      csvLines.push(
        [
          "汇总",
          "",
          "",
          "",
          "",
          "",
          "",
          `订单数: ${group.orderNos.length}`,
          `商品总数: ${group.totalQuantity}`,
          "",
          group.totalQuantity,
          "",
          group.totalAmount,
          `订单号: ${group.orderNos.join("、")}`,
        ].join(",")
      );

      // 添加空行分隔不同地址的配货组
      csvLines.push("");
    });

    return csvLines.join("\n");
  };

  // 下载CSV文件
  const downloadCsv = (content: string, filename: string) => {
    const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");

    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", filename);
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }
  };

  // 导出配货单CSV
  const exportPickingListCSV = async (
    data: PickingGroup[],
    filename = "配货单.csv"
  ) => {
    if (!data || data.length === 0) {
      throw new Error("没有数据可导出");
    }

    isExporting.value = true;

    try {
      const csvContent = buildPickingCsvContent(data);
      downloadCsv(csvContent, filename);
      return true;
    } catch (error) {
      console.error("导出失败:", error);
      throw error;
    } finally {
      isExporting.value = false;
    }
  };

  return {
    isExporting,
    exportPickingListCSV,
  };
}
